# -*- coding: UTF-8 -*-

import sys, os, re

from mutagen.mp3 import MP3
from mutagen.id3 import TIT2, TPE1, TALB, TCON

def ForEachFile(dir, function):
    function(dir)
    if not os.path.isdir(dir):
        return
    for sub in os.listdir(dir):
        sub = os.path.join(dir, sub)
        ForEachFile(sub, function)
        
class CompoundSingleArgFunctor:
    def __init__(self, functors):
        self.__functors = functors
    def __call__(self, obj):
        for functor in self.__functors:
            functor(obj)
            
class MutagenForEachFile:
    def __init__(self, mutagenFunctor):
        self.__mutagenFunctor = mutagenFunctor
    def __call__(self, filePath):
        mutagenInfo = MP3(filePath)
        if not mutagenInfo.tags:
            mutagenInfo.add_tags()
        self.__mutagenFunctor((mutagenInfo, filePath))
        mutagenInfo.save(filePath)

# http://cgit.sukimashita.com/libgpod.git/tree/bindings/python/examples/create_mp3_tags_from_itdb.py?id=9d8212ffb9f20652ffc198e8ef3ed5a945f914a4
def ReplaceMp3TrackNameWithFilename(filePath):
    if not os.path.isfile(filePath):
        return
    ext = os.path.splitext(filePath)[1]
    if ext.lower() != ".mp3":
        return
    title = os.path.splitext(filePath)[0]
    title = os.path.split(title)[1]
    title = title.strip()
    title = title.replace(" ", "-")
    mutagenInfo = MP3(filePath)
    if ("TIT2" in mutagenInfo):
        title = str(mutagenInfo["TIT2"])
    m = re.search("\d\d?-*(.*)", title)
    if m is not None:
        title = m.group(1)
    title = unicode(title, "UTF-8")
    if not mutagenInfo.tags:
        mutagenInfo.add_tags()
    mutagenInfo.tags.add(TIT2(3, title))
    sys.stdout.write(str(mutagenInfo["TIT2"]) + "\n")
#    sys.stdout.write(str(mutagenInfo.items()) + "\n")
    mutagenInfo.save(filePath)

class ReplaceArtist:
    def __init__(self, artist):
        self.__artist = unicode(artist, "UTF-8")

    def __call__(self, filePath):
        if not os.path.isfile(filePath):
            return
        ext = os.path.splitext(filePath)[1]
        if ext.lower() != ".mp3":
            return
        mutagenInfo = MP3(filePath)
        if not mutagenInfo.tags:
            mutagenInfo.add_tags()
#        mutagenInfo.tags.add(TALB(3, self.__artist))
        mutagenInfo.tags.add(TPE1(3, self.__artist))
#        sys.stdout.write(str(mutagenInfo["TALB"]) + "\n") # albom
#        sys.stdout.write(str(mutagenInfo["TCON"]) + "\n") # genre
        sys.stdout.write(str(mutagenInfo["TPE1"]) + "\n")
#        sys.stdout.write(str(mutagenInfo.keys()) + "\n")
        mutagenInfo.save(filePath)

class ReplaceGenre:
    def __init__(self, genre):
        self.__genre = unicode(genre, "UTF-8")

    def __call__(self, filePath):
        if not os.path.isfile(filePath):
            return
        ext = os.path.splitext(filePath)[1]
        if ext.lower() != ".mp3":
            return
        mutagenInfo = MP3(filePath)
        if not mutagenInfo.tags:
            mutagenInfo.add_tags()
        mutagenInfo.tags.add(TCON(3, self.__genre))
        sys.stdout.write(str(mutagenInfo["TCON"]) + "\n") # genre
        mutagenInfo.save(filePath)

class ReplaceAlbom:
    def __init__(self, artist, albomMap):
        self.__artist = unicode(artist, "UTF-8")
        self.__albomMap = {}
        for (k, v) in albomMap.items():
            self.__albomMap[k] = unicode(v, "UTF-8")
        
    def __call__(self, filePath):
        if not os.path.isfile(filePath):
            return
        ext = os.path.splitext(filePath)[1]
        if ext.lower() != ".mp3":
            return
        sys.stdout.write("%s\n" % filePath)
        mutagenInfo = MP3(filePath)
        if not mutagenInfo.tags:
            mutagenInfo.add_tags()
        mutagenInfo.tags.add(TPE1(3, self.__artist))
        albom = "."
        for (k, v) in self.__albomMap.items():
            if filePath.find(k) > -1:
                albom = v
        print albom
        if (albom == "."):
            sys.stderr.write("Warning: albom not found: %s\n" % filePath)
        mutagenInfo.tags.add(TALB(3, albom))
        mutagenInfo.save(filePath)

def main():
#    albomMap = {
#        "1999 - Двери Тамерлана": "dveri-tamerlana",
#        "2003 - Дорога сна": "doroga-sna",
#        "2004 - Master of the Mill": "master-of-the-mill",
#        "2005 - Перевал": "pereval",
#        "2006 - Зов крови": "zov-krovi",
#        "2007 - The Best": "the-best",
#        "2009 - Дикие травы": "dikie-travi",
#        "2009 - Мельница. Новая Коллекция": "nov-kollekzia",
#        "2009 - Леопард в Городе": "leopard-v-gorode",
#        "1999 - Зима": "zima",
#    }
#    ForEachFile(".", ReplaceAlbom("melnitsa", albomMap))
#    albomMap = {
#        "1996-Карусельный-дед": "karuselniy-ded",
#        "2003-Крымские-каникулы": "krimskie-kanikuli",
#        "2003-Страна,-где-ночует-солнце": "strana-gde-nochuet-solnze",
#        "2006-Карусельный-дед": "karuselniy-ded",
#        "В-качестве-приглашенного-музыканта": "priglashenniy-musikant",
##        "": "",
#    }
#    ForEachFile(".", ReplaceAlbom("ivan-smirnov", albomMap))

#    ForEachFile(".", ReplaceMp3TrackNameWithFilename)
#    ForEachFile(".", ReplaceArtist("uma2rman"))
#    ForEachFile(".", ReplaceAlbom(".", {}))
#    ForEachFile(".", ReplaceArtist("nike-borzov"))
#    ForEachFile(".", ReplaceAlbom("tic-tac-toe", { ".": "tic-tac-toe" }))
    ForEachFile(".", CompoundSingleArgFunctor([ReplaceGenre("hip-hop"), ReplaceAlbom("tic-tac-toe", { ".": "tic-tac-toe" })]))

if __name__ == "__main__":
    main()
